<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/18
 * Time: 15:56
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\cha;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\AccountPlatform;
use app\common\model\Channel;
use app\common\model\ChannelOrders;
use app\common\model\Orders;
use app\common\model\SysCountries;
use app\common\service\logistics\ChannelService;

class OrderController extends BaseController
{
    /**
     * 渠道订单列表
     * @date 2020/09/18
     * @author longli
     */
    public function index()
    {
        $this->assign("is_show_label", $this->user->hasPermissions('/cha/order/label'));
        if($this->request->isAjax())
        {
            $order = ChannelOrders::with(['order' => function($query)
            {
                $query->field(['order_id', 'account_id', 'order_sn', 'consignee', 'buyer_first_name', 'buyer_last_name', 'total_qty'])
                    ->with(['account' => function($query){$query->field(['account_id', 'username']);}]);
            }, 'channel' => function($query)
            {
                $query->field(['channel_id', 'channel_name']);
            }, 'country' => function($query)
            {
                $query->field(['code_two', 'name_ch']);
            }])->order("is_cancel, ch_id desc");
            // 处理搜索
            $this->search($order);
            $limit = $this->getPageSize();
            $order = $order->paginate($limit);
            $this->assign('exception', [ChannelOrders::TRACK_STATUS_TIMEOUT, ChannelOrders::TRACK_STATUS_UNRECV,
                ChannelOrders::TRACK_STATUS_EXCEPTION, ChannelOrders::TRACK_STATUS_NONE]);
            $this->assign('is_show_delete', $this->user->hasPermissions('/cha/order/delete'));
            $this->assign("track_status_wait", ChannelOrders::TRACK_STATUS_WAIT);
            $this->assign("track_status_none", ChannelOrders::TRACK_STATUS_NONE);
            $this->assign("track_status_nomapping", ChannelOrders::TRACK_STATUS_NOMAPPING);
            $this->assign("in_track_status", [ChannelOrders::TRACK_STATUS_EXCEPTION, ChannelOrders::TRACK_STATUS_TIMEOUT, ChannelOrders::TRACK_STATUS_RECV]);
            $this->assign('list', $order->getCollection());
            $this->assign('page', $order->render());
            return $this->fetch('lists');
        }
        $this->assign('counties', SysCountries::getCodeNameCh());
        $this->assign("is_show_sync_info", $this->user->hasPermissions('/cha/order/order'));
        $this->assign("track_status", ChannelOrders::$TRACK_STATUS);
        $this->assign("platform", AccountPlatform::getAll());
        $this->assign("channel", Channel::getAll());
        return $this->fetch('index');
    }

    /**
     * 渠道订单搜索
     * @param mixed $order 渠道订单模型
     * @date 2020/09/18
     * @author longli
     */
    private function search($order)
    {
        $platformId = $this->request->request("platform_id", '', 'trim');
        $name = $this->request->request("name", '', 'trim');

        $this->searchModel($order, [
            'eq' => ['channel_id', 'track_status', 'country_code'],
            'times' => ['date']
        ]);

        // 平台搜索
        if(!empty($platformId))
        {
            $order->where("order_id", "in", function($query)use($platformId)
            {
                $query->table(Orders::getTable() . " o")
                        ->join(Account::getTable() . " a", "a.account_id=o.account_id")
                        ->join(AccountPlatform::getTable(). " p", "a.platform_id=p.platform_id")
                        ->where("p.platform_id", $platformId)
                        ->field("o.order_id");
            });
        }
        // 店铺或者账号搜索
        if(!empty($name))
        {
            $order->where("order_id", "in", function($query)use($name)
            {
                $query->table(Orders::getTable() . " o")
                    ->join(Account::getTable() . " a", "a.account_id=o.account_id")
                    ->whereRaw("a.username=? OR store_name=?", [$name, $name])
                    ->field("order_id");
            });
        }
        // 订单号搜索
        if($sn = $this->request->post("sn", '', 'trim'))
        {
            if(Orders::hasSn($sn))
            {
                $order->where("order_id", "in", function($query)use($sn)
                {
                    $query->table(Orders::getTable())
                        ->whereRaw("order_sn=? OR order_no=?", [$sn, $sn])
                        ->field("order_id");
                });
            }
            else
            {
                $order->where('track_num', $sn);
            }
        }
    }

    /**
     * 查看物流详情
     * @return string
     * @date 2021/01/26
     * @author longli
     */
    public function info()
    {
        $chId = $this->request->get("ch_id");
        if(empty($chId)) $this->error("非法请求");
        $chOrder = ChannelOrders::get($chId);
        if(empty($chOrder)) $this->error("物流订单不存在");
        if(empty($chOrder->track_info)) $this->error("暂无物流信息");
        $trackInfo = json_decode($chOrder->track_info, true);
        $this->assign("trackInfo", $trackInfo);
        return $this->fetch("track_info");
    }

    /**
     * 获取物流信息
     * @date 2021/01/26
     * @author longli
     */
    public function track()
    {
        $ids = $this->request->get("ids");
        if(empty($ids)) $this->error("非法请求");
        \think\Console::call('logistics', ["--type=channel", "--ids={$ids}"]);
        $this->success("同步成功");
    }

    /**
     * 同步物流状态到订单
     * @date 2021/02/01
     * @author longli
     */
    public function order()
    {
        $ids = $this->request->get("ids");
        if(empty($ids)) $this->error("非法请求");
        \think\Console::call('syncdata', ["logistics", "--ids={$ids}"]);
        $this->success("同步成功");
    }

    /**
     * 获取面单
     * @date 2020/11/29
     * @author longli
     */
    public function label()
    {
        $ids = $this->request->get("ids");
        if(empty($ids)) $this->error("非法请求");
        $succ = [];
        foreach(ChannelOrders::whereIn("ch_id", $ids)->select() as $chOrder)
        {
            if(!in_array($chOrder->getData('track_status'), [ChannelOrders::TRACK_STATUS_NONE, ChannelOrders::TRACK_STATUS_WAIT, ChannelOrders::TRACK_STATUS_NOMAPPING])
                || !($obj = ChannelService::getInstance()->buildChannelClasses($chOrder->order->channel_id)))
            {
                continue;
            }
            $succ[] = $chOrder->ch_id;
            if(!empty($chOrder->label_url) && (($file = ChannelService::getRootPath($chOrder->label_url)) && is_file($file))) @unlink($file);
            $obj->setOrder($chOrder->order);
            $obj->getLabel();
        }
        !empty($succ) && Tools::containArray(explode(',', $ids), $succ)
            ? $this->success("获取成功")
            : $this->error("获取失败");
    }

    /**
     * 取消申报订单
     * @date 2020/09/25
     * @author longli
     */
    public function cancel()
    {
        $chId = $this->request->get("ch_id");
        if(empty($chId)) $this->error('参数错误');
        $chOrder = ChannelOrders::get($chId);
        if($chOrder->is_cancel == ChannelOrders::IS_YES) $this->error("订单是已取消状态");
        ChannelService::getInstance()->cancelOrder($chOrder->channel_id, $chOrder->order_id)
            ? $this->success("取消成功")
            : $this->error("取消失败");
    }

    /**
     * 删除渠道订单
     * @date 2020/09/18
     * @author longli
     */
    public function delete()
    {
        $orderId = $this->request->request("ids");
        if(empty($orderId)) $this->error('参数错误');
        if(!($order = ChannelOrders::get($orderId))) $this->error('申报订单不存在');
        if($order->getData('track_status') != ChannelOrders::TRACK_STATUS_WAIT) $this->error('已发货的订单无法删除');
        ChannelOrders::destroy($orderId);
        $this->success('删除成功');
    }
}